package online.heycm.rbac.common.converter;

import com.baomidou.mybatisplus.core.metadata.IPage;
import online.heycm.platform.common.entity.result.PageResult;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Function;

/**
 * @author hey
 * @version 1.0
 * @date 2024/1/17 9:45
 */
public class ConvertHelper {

    private ConvertHelper() {
    }

    /**
     * Page 转换
     *
     * @param page     page
     * @param function page元素转换函数
     * @param <T>      出参类型
     * @param <R>      入参类型
     * @return PageResult<T>
     */
    public static <T, R> PageResult<T> page(IPage<R> page, Function<R, T> function) {
        PageResult<T> result = new PageResult<>();
        result.setPage(page.getCurrent());
        result.setPages(page.getPages());
        result.setSize(page.getSize());
        result.setTotal(page.getTotal());
        result.setRecords(list(page.getRecords(), function));
        return result;
    }

    /**
     * List 转换
     *
     * @param collection collection
     * @param function   collection元素转换函数
     * @param <T>        出参类型
     * @param <R>        入参类型
     * @return List<T>
     */
    public static <T, R> List<T> list(Collection<R> collection, Function<R, T> function) {
        if (CollectionUtils.isEmpty(collection)) {
            return Collections.emptyList();
        }
        List<T> records = new ArrayList<>(collection.size());
        for (R record : collection) {
            records.add(function.apply(record));
        }
        return records;
    }

    /**
     * Set 转换
     *
     * @param collection collection
     * @param function   collection元素转换函数
     * @param <T>        出参类型
     * @param <R>        入参类型
     * @return Set<T>
     */
    public static <T, R> Set<T> set(Collection<R> collection, Function<R, T> function) {
        if (CollectionUtils.isEmpty(collection)) {
            return Collections.emptySet();
        }
        Set<T> records = new HashSet<>(collection.size());
        for (R record : collection) {
            records.add(function.apply(record));
        }
        return records;
    }
}
